package com.yilin.tms.data.controller;

import cn.hutool.core.date.DateUtil;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.BarCodeUtils;
import com.yilin.commons.util.CommonUtil;
import com.yilin.commons.util.ImageEditUtils;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.annotation.Explain;
import com.yilin.tms.core.commons.annotation.NotNull;
import com.yilin.tms.core.commons.annotation.SkipLoginVerify;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.data.contracted.ContractBody;
import com.yilin.tms.core.entity.data.receipt.ReceiptOrder;
import com.yilin.tms.core.entity.order.payment.OrderSettlementCost;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrderNoteDetail;
import com.yilin.tms.core.entity.system.system.AppVersion;
import com.yilin.tms.core.entity.truck.TransportLicense;
import com.yilin.tms.core.entity.truck.TravelLicense;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.auth.*;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.entity.user.organize.Cooperate;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.core.remote.IVehicleRemote;
import com.yilin.tms.data.service.IContractService;
import com.yilin.tms.data.service.IReceiptOrderService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 网页视图控制器
 */
@RequestMapping(value = "/data/views/")
@Controller
public class HtmlViewController extends BaseController {

    @Resource
    IContractService contractService;
    @Resource
    IReceiptOrderService receiptService;

    @Resource
    IOrderRemote orderRemote;
    @Resource
    IUserRemote userRemote;
    @Resource
    IVehicleRemote vehicleRemote;

    /**
     * 合同html页面
     */
    @RequestMapping(value = "contractHtml")
    @NotNull("transitOrderId")
    public ModelAndView contractHtml(@Explain("运单ID") String transitOrderId, Boolean pdfPrint) {
        if (pdfPrint == null) pdfPrint = false;
        ContractBody contractBody = contractService.saveOrGetTransitPromise(transitOrderId);
        ParamUtil.isNull(contractBody, "合同无效");
        ModelAndView view1 = new ModelAndView("contract/double_party_contract_pdf");
        ModelAndView view2 = new ModelAndView("contract/third_party_contract_pdf");
        ModelAndView view = contractBody.getMatchmaking() ? view1 : view2;
        view.addObject("contract", contractBody);
        view.addObject("pdfPrint", pdfPrint);
        return view;
    }

    /**
     * 电子回单
     */
    @RequestMapping(value = "elcReceiptOrder")
    @NotNull("transitOrderNoteId")
    public ModelAndView elcReceiptOrder(String transitOrderNoteId, Boolean pdfPrint) {
        if (pdfPrint == null) pdfPrint = false;
        ModelAndView modelAndView = new ModelAndView("order/elc_receipt_order_pdf");
        ReceiptOrder receiptOrder = receiptService.getSaveElcReceiptOrderByNoteId(transitOrderNoteId);
        if (receiptOrder == null) return modelAndView;
        List<TransitOrderNoteDetail> details = ParamUtil.isSuccess(orderRemote.getTransitNoteDetailList(transitOrderNoteId));
        receiptOrder.setTransitOrderNoteDetailList(details);
//        StampCompanySeal stampCompanySeal = ParamUtil.isSuccess(userRemote.getStampCompanySeal(receiptOrder.getPlatId()));
//        modelAndView.addObject("stampCompanySeal", stampCompanySeal);
//        modelAndView.addObject("receiptOrder", receiptOrder);
        TransitOrderNoteDetail first = ArrayUtil.first(receiptOrder.getTransitOrderNoteDetailList());
        String measureUnit = ""; if (first != null) measureUnit = first.getMeasureUnit();
        double totalDeliverMeasure = ArrayUtil.numListAdd(receiptOrder.getTransitOrderNoteDetailList(), TransitOrderNoteDetail::getDeliverMeasure);
        double totalReceiptMeasure = ArrayUtil.numListAdd(receiptOrder.getTransitOrderNoteDetailList(), TransitOrderNoteDetail::getReceiptMeasure);
        modelAndView.addObject("totalDeliverMeasure", CommonUtil.formatDoubleThree(totalDeliverMeasure) + measureUnit);
        modelAndView.addObject("totalReceiptMeasure", CommonUtil.formatDoubleThree(totalReceiptMeasure) + measureUnit);
        String base64FromImage = ImageEditUtils.getBase64FromImage(BarCodeUtils.getBarCodeImage(receiptOrder.getReceiptNo(), 600, 36));
        modelAndView.addObject("barCodeImage", base64FromImage);
        modelAndView.addObject("pdfPrint", pdfPrint);
        return modelAndView;
    }

    /**
     * 电子运单[列表]
     */
    @RequestMapping(value = "elcTransitOrderList")
    @NotNull("transitOrderIds")
    public ModelAndView elcTransitOrderList(String[] transitOrderIds, Boolean pdfPrint) {
        if (pdfPrint == null) pdfPrint = false;
        ModelAndView modelAndView = new ModelAndView("order/elc_transit_order_list_pdf");
        List<TransitOrder> transitOrderList = ParamUtil.isSuccess(orderRemote.getTransitOrderListByIds(String.join(",", transitOrderIds)));
        TransitOrder first = ArrayUtil.first(transitOrderList);
//        transitOrderList.forEach(transitOrder -> {
//            if (!transitOrder.getTransitTruckNo().equals(first.getTransitTruckNo())) throw new BusinessException("请选择同一车辆的运单");
//            if (!transitOrder.getTransitTruckUserId().equals(first.getTransitTruckUserId())) throw new BusinessException("请选择同一司机的运单");
//        });
        modelAndView.addObject("truckerName", first.getRobOrganizeName());
        modelAndView.addObject("truckerPhone", first.getRobAccountPhone());
        modelAndView.addObject("orderCount", transitOrderList.size());
        modelAndView.addObject("totalIncomeCost", ArrayUtil.numListAdd(transitOrderList, TransitOrder::getTruckerActualIncomeCost));
        modelAndView.addObject("generateDate", DateUtil.format(new Date(),"yyyy/MM/dd"));
        modelAndView.addObject("transitOrderList", transitOrderList);
        modelAndView.addObject("pdfPrint", pdfPrint);
        //计算汇总数据
        return modelAndView;
    }

    /**
     * 结算记录[列表]
     */
    @RequestMapping(value = "elcSettlementOrderList")
    @NotNull("orderSettlementCostIds")
    public ModelAndView elcSettlementOrderList(String[] orderSettlementCostIds,String truckerOrganizeName, Boolean pdfPrint) {
        if (pdfPrint == null) pdfPrint = false;
        ModelAndView modelAndView = new ModelAndView("order/elc_trade_order_list_pdf");
        modelAndView.addObject("generateDate", DateUtil.format(new Date(),"yyyy/MM/dd"));
        modelAndView.addObject("pdfPrint", pdfPrint);
        List<OrderSettlementCost> orderSettlementCostList = ParamUtil.isSuccess(orderRemote.getOrderSettlementListByIds(String.join(",", orderSettlementCostIds)));
        if (orderSettlementCostList.isEmpty()) {
            modelAndView.addObject("payeeName",truckerOrganizeName);
            modelAndView.addObject("payeeAccount", "无数据");
            modelAndView.addObject("orderCount", 0);
            modelAndView.addObject("orderPayeeCost", 0);
            return modelAndView;
        }
        OrderSettlementCost first = ArrayUtil.first(orderSettlementCostList);
//        orderSettlementCostList.forEach(settlementCost -> {
//            if (!settlementCost.getPlatId().equals(first.getPlatId())) throw new BusinessException("请选择同一平台的支付单");
//            if (!settlementCost.getTruckerOrganizeId().equals(first.getTruckerOrganizeId())) throw new BusinessException("请选择同一车队");
//        });
        modelAndView.addObject("payeeName", first.getTruckerOrganizeName());
        modelAndView.addObject("payeeAccount", first.getIncomeCapitalAccount());
        modelAndView.addObject("orderCount", orderSettlementCostList.size());
        modelAndView.addObject("orderPayeeCost", ArrayUtil.numListAdd(orderSettlementCostList, OrderSettlementCost::getSettlementCost));
        modelAndView.addObject("orderSettlementCostList", orderSettlementCostList);
        return modelAndView;
    }

    /**
     * 代开协议
     * WEBVIEW 传token
     */
    @RequestMapping(value = "invoiceAgreement")
    public ModelAndView invoiceAgreement(String organizeId,Boolean pdfPrint) {
        if (pdfPrint == null) pdfPrint = false;
        Organize organize;
        if (organizeId == null) {
            organize = ParamUtil.isSuccess(userRemote.getOrganizeById(getLoginUser().getOrganizeId()));
        } else {
            organize = ParamUtil.isSuccess(userRemote.getOrganizeById(organizeId));
        }
        ParamUtil.isNull(organize, "用户不存在");
        ParamUtil.notEquals("无需签订本协议", UserType.truckerUser, organize.getUserType());
        IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(organize.getManagerUserId()));
        ParamUtil.isNull(idCard, "尚未提交身份证认证！");
        ParamUtil.isNull(organize.getSignatureImg(), "尚未提交签名认证！");
        //用户信息
        ModelAndView modelAndView = new ModelAndView("agreement/invoice_agreement");
        modelAndView.addObject("aName", organize.getOrganizeName().replaceAll("（个体）", ""));
        modelAndView.addObject("aPhone", organize.getManagerUserPhone());
        modelAndView.addObject("aCardNo", idCard.getIdCardNo());
        modelAndView.addObject("aAddress", idCard.getAddress());
        if (organize.getAgencySignState() == Organize.AgencySignState.signed) {
            modelAndView.addObject("aSeal", organize.getSignatureImg());
        }
        Organize platOrganize = ParamUtil.isSuccess(userRemote.getOrganizeById(organize.getSuperiorPlatOrganizeId()));
        BusinessLicense platBusinessLicense = ParamUtil.isSuccess(userRemote.getBusinessLicenseByOrganizeId(platOrganize.getId()));
        //平台信息
        modelAndView.addObject("bName", platOrganize.getOrganizeName());
        modelAndView.addObject("bLegalName", platOrganize.getLegalName());
        modelAndView.addObject("bCardNo", platBusinessLicense.getLegalCardNo());
        modelAndView.addObject("bAddress", platOrganize.getAddress());
        modelAndView.addObject("bSeal", platOrganize.getSignatureImg());
        //签订截止日期
        if (organize.getAgencySignTime() == null) {
            modelAndView.addObject("startDate", " --年--年--日 ");
            modelAndView.addObject("endDate", " --年--年--日 ");
        } else {
            modelAndView.addObject("startDate", DateUtil.format(organize.getAgencySignTime(),"yyyy年MM月dd日"));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(organize.getAgencySignTime());
            calendar.add(Calendar.YEAR, 3);
            modelAndView.addObject("endDate", DateUtil.format(calendar.getTime(),"yyyy年MM月dd日"));
        }
        modelAndView.addObject("pdfPrint", pdfPrint);
        return modelAndView;
    }

    /**
     * 车主/用户已材料
     * WEBVIEW 传token
     */
    @RequestMapping(value = "userMaterial")
    public ModelAndView userMaterial(String accountId, Boolean pdfPrint) {
        IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(accountId));
        ModelAndView modelAndView = new ModelAndView("trucker/trucker_info_pdf");
        modelAndView.addObject("idCard",idCard);
        modelAndView.addObject("pdfPrint", pdfPrint);
        return modelAndView;
    }

    /**
     * 司机材料
     * WEBVIEW 传token
     */
    @RequestMapping(value = "driverMaterial")
    public ModelAndView driverMaterial(String accountId, Boolean pdfPrint) {
        IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(accountId));
        DrivingLicense drivingLicense = ParamUtil.isSuccess(userRemote.getDrivingLicenseByUserId(accountId));
        QualificationCert qualificationCert = ParamUtil.isSuccess(userRemote.getQualificationCertByUserId(accountId));
        ModelAndView modelAndView = new ModelAndView("trucker/driver_info_pdf");
        modelAndView.addObject("idCard",idCard);
        modelAndView.addObject("drivingLicense",drivingLicense);
        modelAndView.addObject("qualificationCert",qualificationCert);
        modelAndView.addObject("pdfPrint", pdfPrint);
        return modelAndView;
    }

    /**
     * 车辆材料
     * WEBVIEW 传token
     */
    @RequestMapping(value = "vehicleMaterial")
    public ModelAndView vehicleMaterial(String vehicleId, Boolean pdfPrint) {
        ModelAndView modelAndView = new ModelAndView("trucker/truck_info_pdf");
        TravelLicense travelLicense = ParamUtil.isSuccess(vehicleRemote.getTravelLicenseByVehicleId(vehicleId));
        TransportLicense transportLicense = ParamUtil.isSuccess(vehicleRemote.getTransportLicenseByVehicleId(vehicleId));
        modelAndView.addObject("travelLicense",travelLicense);
        modelAndView.addObject("transportLicense",transportLicense);
        modelAndView.addObject("pdfPrint", pdfPrint);
        return modelAndView;
    }


    /**
     * 货主司机合作协议
     */
    @RequestMapping(value = "cooperateAgreement")
    public ModelAndView cooperateAgreement(String targetOrganizeId) {
        //获取合作关系
        Cooperate cooperate = ParamUtil.isSuccess(userRemote.getCooperate(targetOrganizeId));
        ModelAndView modelAndView = new ModelAndView("agreement/cooperate_agreement");
        modelAndView.addObject("cooperate",cooperate);
        return modelAndView;
    }


    //-------------以下无需登录-----------------------

    /**
     * 用户协议
     */
    @RequestMapping(value = "serviceAgreement")
    @SkipLoginVerify
    public ModelAndView serviceAgreement(AppVersion.AppType appType, String productCode) {
        //货主端/司机端 平台产品码
        //HatchPlatProduct: 产品名称，平台企业名称，等
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatchByCode(productCode));
        ModelAndView modelAndView = new ModelAndView("agreement/service_agreement");
        modelAndView.addObject("platProduct",platProduct);
        modelAndView.addObject("appType",appType);
        return modelAndView;
    }

    /**
     * 隐私协议
     */
    @RequestMapping(value = "privacyAgreement")
    @SkipLoginVerify
    public ModelAndView privacyAgreement(AppVersion.AppType appType, String productCode) {
        //货主端/司机端  平台产品码
        //HatchPlatProduct: 产品名称，平台企业名称，等
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatchByCode(productCode));
        ModelAndView modelAndView = new ModelAndView("agreement/privacy_agreement");
        modelAndView.addObject("platProduct",platProduct);
        modelAndView.addObject("appType",appType);
        return modelAndView;
    }

    /**
     * SDK共享
     */
    @RequestMapping(value = "sdkAgreement")
    @SkipLoginVerify
    public ModelAndView sdkAgreement(AppVersion.AppType appType, String productCode) {
        //货主端/司机端  平台产品码
        HatchPlatProduct platProduct = ParamUtil.isSuccess(userRemote.getPlatProductHatchByCode(productCode));
        ModelAndView modelAndView = new ModelAndView("agreement/sdk_agreement");
        modelAndView.addObject("platProduct",platProduct);
        modelAndView.addObject("appType",appType);
        return modelAndView;
    }


}